import 'package:flutter/material.dart';
import 'package:first_flutter_demo/TabIconView.dart';
import 'package:first_flutter_demo/mine/MinePage.dart';
import 'package:first_flutter_demo/official/OfficialNetWorkPage.dart';
import 'package:first_flutter_demo/similarWords/SimilarWordsPage.dart';
import 'package:first_flutter_demo/home/HomePage.dart';

class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new MainPageState();
  }
}

class MainPageState extends State<MainPage> with TickerProviderStateMixin {
  StatefulWidget currentPage;
  List<TabIconView> tabIconViewArray;
  List<StatefulWidget> pageArray;
  int cuttentIndex = 0;

  //初始化State  有时候网络请求 也必须在这里面
  @override
  void initState() {
    super.initState();
    tabIconViewArray = <TabIconView>[
      new TabIconView(
        icon: new Icon(Icons.assignment),
        title: new Text("首页"),
        vsync: this,
      ),
      new TabIconView(
        icon: new Icon(Icons.all_inclusive),
        title: new Text("寻找近义词"),
        vsync: this, //一定必须的要传入，要不然直接报错  todo   2018.9.4
      ),
      new TabIconView(
          icon: new Icon(Icons.open_with),
          title: new Text("官方Demo"),
          vsync: this),
      new TabIconView(
        icon: new Icon(Icons.people),
        title: new Text("关于我"),
        // ignore: argument_type_not_assignable
        vsync: this,
      )
    ];
    // 相当于 fore 的循环
    for (TabIconView view in tabIconViewArray) {
      view.controller.addListener(rebuild);
    }
    pageArray = <StatefulWidget>[
      new HomePage(),
      new SimilarWordsPage(),
      new OfficialNetWorkPage(),
      new MinePage()
    ];
    currentPage = pageArray[cuttentIndex];
  }

  void rebuild() {
    setState(() {});
  }

  //当该对象从树中永久移除时调用。
  @override
  void dispose() {
    // 相当于 垃圾的释放
    super.dispose();
    for (TabIconView view in tabIconViewArray) {
      view.controller.dispose();
    }
  }

  //Flutter 中 UI 的布局是通过在 dart 文件中构建 Widget 树来实现的。
  //widget 相当于 View，Widget的实例仅仅存在每一帧之间，并且每一帧之间 Flutter都会主动的创建一颗Widget树用于下一帧的渲染。
  //Android 中 View 是可变的，在 Flutter 中的 Widget 是不可变的。这种特性使得 Flutter 中的 Widget 变得十分轻量级
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Center(
          child: currentPage,
        ),
        bottomNavigationBar: buildBar(),
      ),
      theme: new ThemeData.light(),
    );
  }

  buildBar() {
    return new BottomNavigationBar(
      items: tabIconViewArray.map((TabIconView view) => view.item).toList(),
      currentIndex: cuttentIndex,
      fixedColor: Colors.pink,
      type: BottomNavigationBarType.fixed,
      onTap: (int index) {
        setState(() {
          tabIconViewArray[cuttentIndex].controller.reverse();
          cuttentIndex = index;
          tabIconViewArray[cuttentIndex].controller.forward();
          currentPage = pageArray[cuttentIndex];
        });
      },
    );
  }
}
